package com.weifly.weistock.web.controller.record;

import com.weifly.weistock.core.common.ErrorCode;
import com.weifly.weistock.core.common.Result;
import com.weifly.weistock.record.option.OptionConst;
import com.weifly.weistock.record.option.OptionMonitorService;
import com.weifly.weistock.record.option.OptionParseService;
import com.weifly.weistock.record.option.OptionUtils;
import com.weifly.weistock.record.option.domain.GetRecordRequest;
import com.weifly.weistock.record.bo.MergeRecordResult;
import com.weifly.weistock.record.option.domain.OptionRecordDto;
import com.weifly.weistock.record.option.domain.OptionSummaryDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weifly.weistock.core.constant.WeistockConstants.PAGE_LIMIT;

/**
 * 期权记录
 *
 * @author weifly
 * @since 2019/11/23
 */
@Controller
@RequestMapping(value = "/record/option")
public class OptionMonitorController {

    private Logger log = LoggerFactory.getLogger(OptionMonitorController.class);

    @Autowired
    private OptionMonitorService optionMonitorService;

    @Autowired
    private OptionParseService optionParseService;

    /**
     * 导入交割单
     */
    @RequestMapping(value = "/import")
    public String importOrder(HttpServletRequest request, HttpServletResponse response) {
        return "record/option/import";
    }

    /**
     * 上传交割单
     */
    @ResponseBody
    @RequestMapping("/uploadOptionOrder")
    public Result uploadOptionOrder(MultipartHttpServletRequest request) {
        try{
            MultipartFile orderFile = request.getFile("optionOrderFile");
            if(orderFile==null || orderFile.isEmpty()){
                return new Result(ErrorCode.RESULT_PARAM_ERROR, "请上传交割单文件");
            }

            List<OptionRecordDto> recordList = this.optionParseService.parseRecord(orderFile.getInputStream());
            MergeRecordResult mergeResult = this.optionMonitorService.mergeRecordList(recordList);
            return Result.createSuccessResult(mergeResult);
        }catch(Exception e){
            log.error("处理提交数据出错", e);
            return Result.createErrorResult("处理出错: "+e.getMessage());
        }
    }

    /**
     * 期权记录列表
     */
    @RequestMapping(value = "/list")
    public String list(){
        return "record/option/list";
    }

    /**
     * 加载期权记录列表
     */
    @ResponseBody
    @RequestMapping("/getRecordList")
    public Result getRecordList(HttpServletRequest request){
        try{
            String date = request.getParameter("date"); // 发生日期
            String time = request.getParameter("time"); // 成交时间
            String entrust = request.getParameter("entrust"); // 委托编号
            String operationType = request.getParameter("operationType"); // 买卖标志
            String contractCode = request.getParameter("contractCode"); // 合约编码

            // 取记录列表
            GetRecordRequest queryRequest = new GetRecordRequest();
            queryRequest.setDate(date);
            queryRequest.setTime(time);
            queryRequest.setEntrust(entrust);
            queryRequest.setOperationType(OptionConst.OperationType.getEnumByName(operationType));
            queryRequest.setContractCode(contractCode);
            queryRequest.setFilterContractCode(request.getParameter("filterContractCode"));
            queryRequest.setFilterPair(request.getParameter("filterPair"));
            queryRequest.setLimit(PAGE_LIMIT+1);
            List<OptionRecordDto> recordList = this.optionMonitorService.getRecordList(queryRequest);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("haveMore", recordList.size()>PAGE_LIMIT);

            List<Map<String, Object>> recordInfoList = new ArrayList<>();
            if(recordList.size()>0){
                DecimalFormat decimalFormat = new DecimalFormat("0.##");
                for(int i=0;i<recordList.size();i++){
                    OptionRecordDto recordDto = recordList.get(i);
                    Map<String, Object> recordInfo = new HashMap<>();
                    recordInfo.put("date", recordDto.getDate());
                    recordInfo.put("time", recordDto.getTime());
                    recordInfo.put("entrustCode", recordDto.getEntrustCode());
                    recordInfo.put("contractName", recordDto.getContractName());
                    recordInfo.put("contractCode", recordDto.getContractCode());
                    recordInfo.put("businessName", recordDto.getBusinessName().getName());
                    recordInfo.put("operationType", recordDto.getOperationType().getName());
                    recordInfo.put("holdPosition", recordDto.getHoldPosition().getName());
                    recordInfo.put("tradePrice", recordDto.getTradePrice());
                    recordInfo.put("tradeNumber", recordDto.getTradeNumber());
                    recordInfo.put("tradeAmount", recordDto.getTradeAmount());
                    recordInfo.put("feeService", recordDto.getFeeService());
                    recordInfo.put("clearAmount", recordDto.getClearAmount());
                    recordInfo.put("afterAmount", recordDto.getAfterAmount());
                    recordInfo.put("afterNumber", recordDto.getAfterNumber());
                    recordInfo.put("diffAmount", recordDto.getDiffAmount());
                    recordInfo.put("pair", OptionUtils.makePairAttr(recordDto));
                    recordInfoList.add(recordInfo);
                }
                // 只返回limit条记录
                if(recordInfoList.size()>PAGE_LIMIT){
                    recordInfoList = recordInfoList.subList(0, PAGE_LIMIT);
                }
            }
            dataMap.put("recordList", recordInfoList);

            return Result.createSuccessResult(dataMap);
        }catch(Exception e){
            log.error("加载期权记录列表出错", e);
            return Result.createErrorResult("加载记录列表出错: " + e.getMessage());
        }
    }

    /**
     * 期权统计
     */
    @RequestMapping(value = "/summary")
    public String summary(){
        return "record/option/summary";
    }

    /**
     * 加载期权统计
     */
    @ResponseBody
    @RequestMapping("/loadSummaryInfo")
    public Result loadSummaryInfo(){
        try{
            OptionSummaryDto optionSummaryDto = this.optionMonitorService.loadSummaryInfo();
            return Result.createSuccessResult(optionSummaryDto);
        }catch(Exception e){
            log.error("加载期权统计出错", e);
            return Result.createErrorResult("加载期权统计出错: " + e.getMessage());
        }
    }
}
